<?php

namespace App\Http\Controllers\Web\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Web\StoreRequest;
use App\Models\Examination;
use App\Models\StudentResult;
use App\Transformers\Web\WebStudentResultTransformer;
use Carbon\Carbon;
use Dingo\Api\Http\Response;

class EmigratedController extends Controller
{
    /**
     * 我的闯关
     *
     * @return Response
     */
    public function index()
    {
        $data = StudentResult::query()
            ->select('id', 'examination_id', 'already_num', 'all_num', 'created_at', 'submit_type', 'username', 'subject_id')
            ->where([
                ['type', 3],
                ['user_id', auth()->id()]
            ])
            ->with('subject:id,name')
            ->orderBy('created_at', 'desc')
            ->paginate($this->pageLimit());

        return $this->response->paginator($data, new WebStudentResultTransformer());
    }

    /**
     * 去闯关
     *
     * @return Response|void
     */
    public function get(StoreRequest $request)
    {
        $subjectId = $request->input('subject_id');
        // 获取 状态为 1 类型 1 的考场
        $exam = Examination::query()
            ->select(['id', 'name', 'passing_mark', 'subject_id', 'category_id', 'start_time', 'test_list_id', 'timer', 'over_time', 'show_result',
                'show_answer', 'mouse_out', 'mouse_out_num', 'status'])
            ->where([
                ['type', 3],
                ['status', 1],
                ['examination_mode', 0],
            ])
            ->orWhere([
                ['type', 3],
                ['status', 1],
                ['examination_mode', 1],
                ['peoples', 'like', '%,' . auth()->id() . ',%'],
            ])
            ->with('subject:id,name')
            ->with('category:id,name')
            ->when($subjectId, function ($query) use ($subjectId){
                $query->where('subject_id', $subjectId);
            })
            ->orderBy('created_at', 'desc')
            ->firstOrFail();

        if (!$exam) {
            return $this->response->errorBadRequest('没有相关的闯关哦');
        }

        // 截止进场时间
        if (Carbon::now()->gt(Carbon::parse($exam->over_time))) {
            return $this->response->errorBadRequest('闯关已经截止进场');
        }

        $test = json_decode(json_encode($exam->testList), true);
        $allTest = [];
        $num = 0;
        $timer = 0;
        foreach ($test as $key => $value) {
            if ($key == 'random') {
                if (is_array($value) && !empty($value)) {
                    foreach ($value as $k => $v) {
                        if (is_array($v) && !empty($value)) {
                            $nums = array_column($v, 'num');
                            if (!empty($nums)) {

                                $num += array_sum($nums);
                                $timer += array_sum($nums) * 500;
                            }
                        }
                    }
                }
            }
            if ($key == 'fixed') {
                if (is_array($value) && !empty($value)) {
                    $num += count($value);
                    $timer += count($value) * 500;
                }
            }
        }

        $allTest['num'] = $num;
        $allTest['timer'] = $timer;
        return $this->response->array(['exam' => $exam, 'test' => $allTest]);
    }

    /**
     * 开始闯关
     *
     * @return Response
     */
    public function store(StoreRequest $request)
    {
        $request->validate([
            'examination_id' => ['exists:examinations,id,status,1,type,3']
        ], [
            'examination_id.exists' => '请输入符合条件的闯关试卷'
        ]);

        $studentResult = createStudentResult($request);

        // 获取闯关题目
        $content = $studentResult->content;

        // 获取第一关
        $data = array_shift($content);
        $data['emigrated_id'] = $studentResult['id'];

        return $this->response->array(['data' => $data]);
    }

    /**
     * 下一关
     *
     * @param StoreRequest $request
     * @return Response|void
     */
    public function next(StoreRequest $request)
    {
        $request->validate([
            'examination_id' => ['exists:examinations,id,status,1,type,3'],
            'question_id' => 'required|exists:questions,id',
            'answer' => 'required',
            'fraction' => 'required'
        ]);

        if (!$request->has('emigrated_id')) {
            return $this->response->error('请填写闯关id', 422);
        }

        $request->offsetSet('id', $request->input('question_id'));

        $studentResult = StudentResult::query()
            ->where([
                ['id',  $request->input('emigrated_id')],
                ['user_id',  $this->adminUser()->id()],
                ['examination_id', $request->input('examination_id')],
                ['submit_type', 4]
            ])
            ->pimp()
            ->first();

        if (empty($studentResult)) {
            return $this->response->errorBadRequest('闯关已结束');
        }

        $aleady_num = $studentResult->already_num ?: 1;

        if (Carbon::now()->gt($studentResult->created_at->addSeconds($aleady_num * 500))) {
            $studentResult->update(['submit_type' => 1]);
            return $this->response->errorBadRequest('闯关已超时');
        }

        $correct = autoCorrect($request->all());

        if (is_array($correct) && (!$correct['is_true'] || $correct['is_true'] == 2)){
            $studentResult->update(['submit_type' => 1]);
            return $this->response->errorBadRequest('答题错误，闯关已结束');
        }
        // 获取下一题
        $data = [];

        $alreadyNum = 0;
        $content = $studentResult->content;
        foreach ($content as $key => &$item) {
            if ($item['id'] == $correct['id']) {
                $alreadyNum = $key;
                $item['answer'] = $correct['answer'];
                $item['is_true'] = $correct['is_true'];
                $item['fraction'] = $correct['fraction'];

                if (isset($content[$key + 1])) {
                    $data = $content[$key + 1];
                } else {
                    $studentResult->update(['submit_type' => 0]);
                }
            }
        }

        $studentResult->update(['content' => $content, 'already_num' => $alreadyNum]);

        return $this->response->array(['data' => $data]);
    }
}
